<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/5/28
 * Time: 0:08
 */

namespace Organize\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use Platform\Models\Organize\LeaderPermission;

class LeaderResources extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'username' => $this->username,
            'name' => $this->name,
            'avatar' => $this->avatar_url,
            'created_at' => $this->created_at->toDateTimeString(),

            'organize' => [
                'id' => optional($this->organize)->id,
                'name' => optional($this->organize)->name,
            ],
            'role' => new RoleResources($this->whenLoaded('role')),

            /** 判断是否预加载角色，并且在访问用户列表时让 permission 字段隐藏 */
            $this->mergeWhen(
                $this->whenLoaded('role')
                && (strstr(request()->url(),route('organize::leaders.index').'/')
                    || strstr(request()->url(),route('admin::organizes_leaders.index').'/'))
                ,function(){
                    $permissions = LeaderPermission::get(['id','name','module','uri','method']);
                    $admin_permissions = $this->allPermissions();
                    $permissions =  LeaderPermission::makeData($permissions,$admin_permissions);
                    return  ['permissions' => $permissions];
                }),
        ];
    }
}